package client;

import java.io.*;
import java.net.Socket;

/**
 * @author: liuchong
 * @create: 2023/2/22 15:04
 * @description:
 */
public class QuotationClientTread extends Socket{

    private static final String SERVER_IP = "127.0.0.1";
    private static final int SERVER_PORT = 8899;
    private Socket client;
    private FileInputStream fileInputStream;
    private OutputStreamWriter outputStreamWriter;

    public QuotationClientTread() throws IOException {
        super(SERVER_IP, SERVER_PORT);
        this.client = this;
        System.out.println("Client[port:" + client.getLocalPort() + "] 成功连接服务端");
    }

    /**
     * 向服务端发送文件
     * @throws Exception
     */
    public void sendFile(String filePath) throws Exception {
        try {
            long startTime = System.currentTimeMillis();
            File file = new File(filePath);
            if(file.exists()) {
                fileInputStream = new FileInputStream(file);
                BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream));
                outputStreamWriter = new OutputStreamWriter(client.getOutputStream());
//                outputStreamWriter.write(file.getName());
//                outputStreamWriter.flush();
                BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
//                bufferedWriter.write(file.getName());
                // 开始发送文件
                System.out.println("======== 开始发送文件 ========");
                int length = 0;
                long progress = 0;
                String temp;
                while((temp = br.readLine()) != null) {
                    System.out.println(temp);
                    bufferedWriter.write(temp + System.currentTimeMillis() +"\n");
                    bufferedWriter.flush();
                    Thread.currentThread().sleep(1);
                    length++;
                    progress += length;
                    System.out.print("| " + (100*progress/file.length()) + "% |");
                }

                System.out.println("======== 文件发送成功 ========");
                long endTime = System.currentTimeMillis();
                System.out.println("程序运行时间： " + (endTime - startTime) + "ms");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream != null)
                fileInputStream.close();
            if(outputStreamWriter != null)
                outputStreamWriter.close();
            client.close();
        }
    }
}
